package com.sright.bcard.common.service.share.base.dao;

import com.dangdang.ddframe.rdb.sharding.keygen.DefaultKeyGenerator;
import com.sright.bcard.common.service.share.exception.base.DaoErrorException;
import org.springframework.dao.DuplicateKeyException;

import java.util.Date;

/**
 * BaseDAOImpl
 */
public abstract class BaseDAOImpl<T extends BaseDO> implements BaseDAO<T> {

    /**
     * 获取mapper的具体实现类，留待子类实现
     *
     * @return
     */
    protected abstract BaseMapper<T> getObjMapper();


    @Override
    public T selectById(Long id) {
        return getObjMapper().selectByPrimaryKey(id);
    }

    @Override
    public Long insert(T t) {
        try {
            Date date = new Date();
            t.setCreatedAt(date);
            t.setUpdatedAt(date);
            t.setIsDelete(0);
            int i = getObjMapper().insert(t);
            if (i > 0) {
                return t.getId();
            }
            return 0L;
        } catch (DuplicateKeyException e) {
            throw new DaoErrorException("重复数据", e);
        }
    }

    @Override
    public Long insertSelective(T t) {
        try {
            Date date = new Date();
            t.setCreatedAt(date);
            t.setUpdatedAt(date);
            t.setIsDelete(0);
            int i = getObjMapper().insertSelective(t);
            if (i > 0) {
                return t.getId();
            }
            return 0L;
        } catch (DuplicateKeyException e) {
            throw new DaoErrorException("重复数据", e);
        }
    }

    @Override
    public Boolean updateAll(T t) {
        if (t.getUpdatedAt() == null) {
            t.setUpdatedAt(new Date());
        }
        if (t.getIsDelete() == null) {
            t.setIsDelete(0);
        }
        int i = getObjMapper().updateByPrimaryKey(t);
        if (i > 0) {
            return true;
        }
        return false;
    }


    @Override
    public Boolean updateSelective(T t) {
        if (t.getUpdatedAt() == null) {
            t.setUpdatedAt(new Date());
        }
        if (t.getIsDelete() == null) {
            t.setIsDelete(0);
        }
        int i = getObjMapper().updateByPrimaryKeySelective(t);
        if (i > 0) {
            return true;
        }
        return false;
    }

    private DefaultKeyGenerator defaultKeyGenerator = new DefaultKeyGenerator();

    protected Long generateKey(){
        return defaultKeyGenerator.generateKey().longValue();
    }


}
